package com.springboot.tools.page.dao;

import com.springboot.tools.page.Constant;
import com.springboot.tools.page.model.Pager;
import com.springboot.tools.page.model.Student;
import com.springboot.tools.page.util.JdbcUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class SublistStudentDaoImpl implements StudentDao {

    @Override
    public Pager<Student> findStudent(Student serchModel, int pageNum, int pageSize) {
        List<Student> allStudnetList = getAllStudent(serchModel);
        return new Pager<Student>(pageNum, pageSize, allStudnetList);
    }

    private List<Student> getAllStudent(Student searchModel) {
        List<Student> result = new ArrayList<Student>();
        List<Object> paramList = new ArrayList<Object>();
        String stuName = searchModel.getStuName();
        int gender = searchModel.getGender();
        StringBuilder sql = new StringBuilder("select * from t_student where 1=1");
        if (stuName != null && !stuName.equals("")) {
            sql.append(" and stu_name like ?");
            paramList.add("%" + stuName + "%");
        }
        if (gender == Constant.GNEDER_MALE || gender == Constant.GNEDER_FEMALE) {
            sql.append(" and gender = ?");
            paramList.add(gender);
        }
        JdbcUtil jdbcUtil = new JdbcUtil();
        try {
            jdbcUtil.getConnection();
            List<Map<String, Object>> mapList = jdbcUtil.findResult(sql.toString(), paramList);
            if (null != mapList) {
                for (Map<String, Object> map : mapList) {
                    Student s = new Student(map);
                    result.add(s);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getLocalizedMessage());
        } finally {
            jdbcUtil.releaseConn();
        }
        return result;
    }
}
